<?php

namespace App\Http\Middleware\Admin\V1;

use Closure;
use App\Models\V1\Admin;
use App\Exceptions\Admin\V1\GeneralException;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;

class PermissionCheckMiddleware
{
    /**
     * @expalin 权限校验
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws GeneralException
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/11:50
     */
    public function handle($request, Closure $next)
    {
        $routeName = str_replace('Admin::', '', $request->route()->getName());

        if ($routeName) {
            /** @var Admin $admin */
            $admin = auth()->user();
            if ($admin->isSuper() == false && $admin->roles()->where('is_super', 1)->exists() == false) {
                try {
                    $hasPermission = $admin->hasPermissionTo($routeName);
                    if (!$hasPermission) {
                        throw new GeneralException(GeneralException::GENERAL_SYSTEM_PERMISSION_INVALID);
                    }
                }
                catch ( PermissionDoesNotExist $exception ) {
                    // 不存在默认通过...
                }
            }
        }

        return $next($request);
    }
}
